package com.dhcc.DRGsHosp.facade.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.inject.Named;

import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.koala.commons.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.DrgsIndexCalApplication;
import com.dhcc.DRGsHosp.application.EsIndexApplication;
import com.dhcc.DRGsHosp.core.domain.EsIndex;
import com.dhcc.DRGsHosp.facade.EsIndexFacade;
import com.dhcc.DRGsHosp.facade.dto.EsIndexDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.EsIndexAssembler;

@Named("esdFacadeImplHuangju201801030")
public class EsIndexFacadeImpl implements EsIndexFacade{

	@Autowired
	private EsIndexApplication  application;
	
	@Autowired
	private DrgsIndexCalApplication  drgsIndexApplication;
	
	
	private QueryChannelService queryChannel;
	private QueryChannelService getQueryChannelService(){
	       if(queryChannel==null){
	          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
	       }
	     return queryChannel;
	    }
		
		public InvokeResult creatEsIndex(EsIndexDTO esdDTO) {
			EsIndex dvm = application.getEsIndex(esdDTO.getSalesId());
			if(null == dvm){
				application.creatEsIndex(EsIndexAssembler.toEntity(esdDTO));
				return InvokeResult.success();
			}else{
				return InvokeResult.failure("此ES服务ID已存在！");
			}
		}
	     
		public InvokeResult updateEsIndex(EsIndexDTO esdDTO) {
			application.updateEsIndex(EsIndexAssembler.toEntity(esdDTO));
			return InvokeResult.success();
		}
		
		public InvokeResult removeEsIndexs(String[] salesIds) {
			Set<EsIndex> esds= new HashSet<EsIndex>();
			for ( String salesId : salesIds) {
				EsIndex esd = application.getEsIndex(salesId);
				esds.add(esd);
			}
			application.removeEsIndexs(esds);
			return InvokeResult.success();
		}
	
	
		public Page<EsIndexDTO> pageQueryEsIndex(int currentPage, int pageSize) {
			try {
			   	StringBuilder jpql = new StringBuilder("select _esd from EsIndex _esd");        
			   	Page<EsIndex> pages = getQueryChannelService().createJpqlQuery(jpql.toString()).setPage(currentPage, pageSize).pagedList();
		        return new Page<EsIndexDTO>(pages.getStart(), pages.getResultCount(),pageSize, EsIndexAssembler.toDTOs(pages.getData()));
			}catch(Exception e) {
				e.printStackTrace();
				return new Page<EsIndexDTO>(pageSize, pageSize, pageSize, null);
			}
		}

		/**
	     *  
	     *  isSalesIdExist.  
	     *  @Description：系统使用es的业务ID是否存在
	     *  @Author huangju
	     *  @param salesId
	     *  @return 
	     *  @Date:2018年10月30日
	     */	
		@Override
		public boolean isSalesIdExist(String esIndex, String salesName) {
			return application.isSalesIdExist(esIndex,salesName) ;
		}

}
